package com.seemygo.shop.cloud.mq.listener;

import com.seemygo.shop.cloud.core.WebSocketSessionManager;
import com.seemygo.shop.cloud.mq.msg.MQConstants;
import com.seemygo.shop.cloud.mq.msg.SeckillFailedMsg;
import com.seemygo.shop.cloud.mq.msg.SeckillSuccessMsg;
import com.seemygo.shop.cloud.resp.CodeMsg;
import com.seemygo.shop.cloud.resp.Result;
import com.seemygo.shop.cloud.util.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(
        topic = MQConstants.SECKILL_FAILED_DEST,
        selectorExpression = MQConstants.SECKILL_FAILED_TAG,
        consumerGroup = MQConstants.SECKILL_FAILED_CONSUMER_GROUP
)
public class SeckillFailedMQListener implements RocketMQListener<SeckillFailedMsg> {




    @Override
    public void onMessage(SeckillFailedMsg message) {
         log.info("[秒杀成功消息] 收到秒杀订单成功消息", JSONUtil.toJSONString(message));
        Result<?> result = Result.error(message.getCodeMsg());
        boolean ret ;
        int count = 0, max = 3;
        do{
            ret = WebSocketSessionManager.INSTANCE.sendMsg(message.getUuid(), result);
            if(!ret){
                try {
                    Thread.sleep(10L);
                } catch (Exception e) {
                }
            }
           count++;
        } while (!ret && count <= max);
    }
}
